//
// Created by root on 6/24/17.
//

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <time.h>
#include "utils.h"
#include "constants.h"

int match_regex(char* regex, char* text) {
    regex_t regex_comp;
    int reti;
    char msgbuf[100];

    reti = regcomp(&regex_comp, regex, REG_EXTENDED);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        return FALSE;
    }

    reti = regexec(&regex_comp, text, 0, NULL, 0);
    if (!reti) {
        regfree(&regex_comp);
        return TRUE;
    }
    else if (reti == REG_NOMATCH) {
        regfree(&regex_comp);
        return FALSE;
    }
    else {
        regerror(reti, &regex_comp, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        regfree(&regex_comp);
        return FALSE;
    }
}

char** match_regex_groups(char* regex, int groups, char* text) {
    regex_t regex_comp;
    regmatch_t group[groups];
    int reti;
    char msgbuf[100];
    reti = regcomp(&regex_comp, regex, REG_EXTENDED);
    if (reti) {
        fprintf(stderr, "Could not compile regex\n");
        return NULL;
    }

    reti = regexec(&regex_comp, text, groups, group, 0);
    if (!reti) {
        char* *result = (char**)malloc((groups + 1) * sizeof(char *));
        unsigned int g = 0;
        for (g = 0; g < groups; g++) {
            if (group[g].rm_so == (size_t)-1)
                break;  // No more groups

            char sourceCopy[strlen(text) + 1];
            strcpy(sourceCopy, text);
            sourceCopy[group[g].rm_eo] = 0;
            *(result + g) = strdup(sourceCopy + group[g].rm_so);
        }
        *(result + g) = NULL;

        regfree(&regex_comp);
        return result;
    }
    else if (reti == REG_NOMATCH) {
        regfree(&regex_comp);
        return NULL;
    }
    else {
        regerror(reti, &regex_comp, msgbuf, sizeof(msgbuf));
        fprintf(stderr, "Regex match failed: %s\n", msgbuf);
        regfree(&regex_comp);
        return NULL;
    }
}


/*
获得当前时间字符串
@param buffer [out]: 时间字符串
@return 空
*/
void get_local_time(char* buffer) {
    time_t rawtime;
    struct tm* timeinfo;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    sprintf(buffer, "[%04d-%02d-%02d %02d:%02d:%02d] ",
            (timeinfo->tm_year+1900), timeinfo->tm_mon, timeinfo->tm_mday,
            timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
}

char* concatenate(char* str, char* append) {
    if (append == NULL || strcmp(append, "") == 0) {
        return str;
    }
    int length = strlen(str) + strlen(append) + 1;
    str = realloc(str, length * sizeof(char));
    str = strcat(str, append);
    return str;
}
